package com.woniu.controller;

import com.woniu.been.entity.Courses;
import com.woniu.been.entity.UserOrders;
import com.woniu.been.entity.vo.UserOrdersVo;
import com.woniu.service.TeachersService;
import com.woniu.service.UserOrdersService;
import com.woniu.utils.IDUtils;
import com.woniu.utils.PageResult;
import com.woniu.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("order")
@CrossOrigin
public class UserOrdersController {
    @Autowired
    private UserOrdersService userOrdersService;

    @Autowired
    private TeachersService teachersService;

    @RequestMapping("findAll")
    public ResponseResult findAll(UserOrders userOrders){

        List<UserOrders> result = userOrdersService.findAll(userOrders);
        return ResponseResult.success(result);
    }
    @PostMapping("payOrder")
    public ResponseResult payOrder(@RequestBody UserOrders userOrders) {
        //将userOrders.courseIds 通过‘,’分割Integer数组
        String str = "";
        try {
            String[] courseIdStrs = userOrders.getCourseIds().split(",");
            Integer[] courseIds = new Integer[courseIdStrs.length];
            //拆分ids集合
            String[] orderIds = userOrders.getOrderIds().split(",");
            Integer[] orderIdsInt = new Integer[orderIds.length];
            for (int i = 0; i < courseIdStrs.length; i++) {
                courseIds[i] = Integer.valueOf(courseIdStrs[i].trim());
                orderIdsInt[i] = Integer.valueOf(orderIds[i].trim());

                userOrders.setCourseId(courseIds[i]);
                userOrders.setOrderId(orderIdsInt[i]);
                userOrdersService.payOrder(userOrders);
            }

            return ResponseResult.success(userOrders);
        } catch (NumberFormatException e) {
            return ResponseResult.fail(400,"订单支付失败");
        }


    }
    @DeleteMapping("delById")
    public ResponseResult delById(String id) {
        userOrdersService.delById(id);
        return ResponseResult.success();
    }
    @DeleteMapping("deleteBacthed")
    public ResponseResult deleteBacthed(String ids) {
        userOrdersService.deleteBacthed(ids);
        return ResponseResult.success();
    }
//    @PostMapping("insertOrder")
//    public ResponseResult insertOrder(@RequestBody UserOrders userOrders) {
//        userOrdersService.insertOrder(userOrders);
//        return ResponseResult.success();
//    }
    /**
     *新增订单
     *@param userOrders  id用courseIds传入  然后拆分
     * @return cxz
     */
    @PostMapping("insertOrder")
    public ResponseResult insertOrder(@RequestBody UserOrders userOrders) {
        //将userOrders.courseIds 通过‘,’分割Integer数组
        userOrders.setOrderNumber(IDUtils.randomId());
        String str = "";
        Map<String, String> map = new HashMap<>();


        try {
            String[] courseIdStrs = userOrders.getCourseIds().split(",");
            Integer[] courseIds = new Integer[courseIdStrs.length];

            for (int i = 0; i < courseIdStrs.length; i++) {
                courseIds[i] = Integer.valueOf(courseIdStrs[i].trim());
            }
            //将paymentAmounts 通过‘,’分割Double数组
            String[] paymentAmountStrs = userOrders.getPaymentAmounts().split(",");
            Double[] paymentAmounts = new Double[paymentAmountStrs.length];

            for (int i = 0; i < paymentAmountStrs.length; i++) {
                paymentAmounts[i] = Double.valueOf(paymentAmountStrs[i].trim());
            }


            for(int i=0;i<courseIds.length;i++){
                userOrders.setCourseId(courseIds[i]);
                userOrders.setPaymentAmount(paymentAmounts[i]);
                str = userOrdersService.insertOrder(userOrders);
                System.out.println("..........................."+str);

            }
            if(str.equals("下单成功")){
                map.put("msg", str);
                map.put("orderNumber", userOrders.getOrderNumber());
                System.out.println("这个订单的单号"+userOrders.getOrderNumber());
            }else{
                UserOrders orderNumber= userOrdersService.findNumberByCourseId(courseIds[0],userOrders.getUserId());
                map.put("msg", str);

                map.put("orderNumber", orderNumber==null?null:orderNumber.getOrderNumber());
            }
            return ResponseResult.success(map);
        } catch (NumberFormatException e) {
            return ResponseResult.fail(400,"订单添加失败");
        }


    }

    /**
     * 只能修改订单状态
     * @param userOrder
     * @return cxz
     */
    @PostMapping("updateById")
    public ResponseResult updateById(@RequestBody UserOrders userOrder) {
        userOrdersService.updateById(userOrder);
        return ResponseResult.success();
    }
    /**
     * 修改订单状态
     */

    /*
    * 分页查询订单
    * */
    @PostMapping("QueryOrdersByPagination")
    public ResponseResult<PageResult> QueryOrdersByPagination(@RequestBody UserOrdersVo userOrdersVo) {
        System.out.println("============"+userOrdersVo+"=============");
        Integer role = teachersService.findRoleByTeacherId(userOrdersVo.getTeacherId());
        System.out.println("============"+role+"=============");
        if(role==1){
            userOrdersVo.setTeacherId(null);
            PageResult result = userOrdersService.QueryOrdersByPagination(userOrdersVo,userOrdersVo.getPageNum(), userOrdersVo.getPageSize());
            return ResponseResult.success(result);
        }else if(role==2){
            PageResult result = userOrdersService.QueryOrdersByPagination(userOrdersVo,userOrdersVo.getPageNum(), userOrdersVo.getPageSize());
            return ResponseResult.success(result);
        }else{
            return ResponseResult.fail(400,"没有权限");
        }
    }

    /*
    * 平均客单价（已完成订单）
    * */
    @GetMapping("averageOrderPrice")
    public ResponseResult averageOrderPrice(){
        Double averageOrderPrice = userOrdersService.averageOrderPrice();
        return ResponseResult.success(averageOrderPrice);
    }

    /*
    * 总销售额（已完成订单）
    * */
    @GetMapping("totalSales")
    public ResponseResult totalSales(){
        Double totalSales = userOrdersService.totalSales();
        return ResponseResult.success(totalSales);
    }

    /*
    * 总订单量（含待付款 / 已完成）
    * */
    @GetMapping("totalOrders")
    public ResponseResult totalOrders(){
        Integer totalOrders = userOrdersService.totalOrders();
        return ResponseResult.success(totalOrders);
    }

    /*
    * 课程销量排名（按订单数
    * */
    @GetMapping("courseSalesRanking")
    public ResponseResult courseSalesRanking(){
        List<Courses> courseSalesRanking = userOrdersService.courseSalesRanking();
        for (Courses course:courseSalesRanking){
            System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"+course);
        }
        return ResponseResult.success(courseSalesRanking);
    }

    /*
    * 课程销售额排名（按收入）
    * */
    @GetMapping("courseSalesRankingByIncome")
    public ResponseResult courseSalesRankingByIncome(){
        List<Courses> courseSalesRankingByIncome = userOrdersService.courseSalesRankingByIncome();
        return ResponseResult.success(courseSalesRankingByIncome);
    }

}
